package cn.itcast.com.network.udp.v2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Sender {
    public static void main(String[] args) throws IOException {

        //获取键盘的输入
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        //创建套接字对象
        DatagramSocket datagramSocket = new DatagramSocket(8080);
        //创建一个用于接受数据的数据报包
        byte[] bytes = new byte[1024];
        //创建一个字符串接受键盘的输入
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);
        String data;
        while ((data = bufferedReader.readLine()) != null){
            sendData(datagramSocket, data);
            datagramSocket.receive(datagramPacket);
            //将接受到的数据包写入字符输出
            parseData(datagramPacket);
            //如果发送的是886,则中断
            if (data.equals("886")){
                break;
            }

        }
        datagramSocket.close();
    }

    private static void sendData(DatagramSocket datagramSocket, String data) throws IOException {
        //将获得的数据转换成字节数组，方便待会的传参
        byte[] dataBytes = data.getBytes();
        //获得本机的ip地址
        InetAddress localHost = InetAddress.getLocalHost();
        //将参数都写入Packet中
        DatagramPacket datagramPacket = new DatagramPacket(dataBytes, 0, dataBytes.length, localHost, 8282);

        datagramSocket.send(datagramPacket);
    }
    //返回值用来判断是否为886从而中断进程
    private static String parseData(DatagramPacket datagramPacket) {
        //输出数组
        //获得字节数组数据
        byte[] data = datagramPacket.getData();
        //获得偏移量
        int offset = datagramPacket.getOffset();
        //获得字节个数
        int length = datagramPacket.getLength();
        //通过解析获得文字
        String s = new String(data,offset,length);
        //获得发送方的ip地址
        InetAddress address = datagramPacket.getAddress();
        //获得发送方的端口号
        int port = datagramPacket.getPort();
        System.out.println("接受来自 "+address+":"+port+"  "+s);
        return s;
    }
}
